package cn.lee.cplibrary.util.video.videocompressor;

import android.os.Handler;
import android.os.Looper;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import cn.lee.cplibrary.util.LogUtil;

/**
 * 在需要的地方调用压缩：如 Activity 的 onCreate调用
 * VideoCompress videoCompress = new VideoCompress(quality);
 * videoCompress.compressVideo(inputPath, outputPath,listener);
 * 在 Activity的 onDestroy 中调用
 * videoCompress.closeExecutor();
 * Created by ChrisLee
 * Date: 2025/8/20
 */
public class VideoCompress {
    private ExecutorService executorService;
    private Handler mainHandler;

    //初始化传入
    private CompressListener mListener;
    private int mQuality;

    /**
     * @param quality 值为：VideoController.COMPRESS_QUALITY_HIGH，
     *                VideoController.COMPRESS_QUALITY_MEDIUM，
     *                VideoController.COMPRESS_QUALITY_LOW
     */
    public VideoCompress(int quality) {
        this.mQuality = quality;
    }

    public VideoCompress() {
        this(VideoController.COMPRESS_QUALITY_LOW);
    }

    public void compressVideo(String srcPath, String destPath, CompressListener listener) {
        init(srcPath, destPath, listener);
    }

    protected void init(String srcPath, String destPath, CompressListener listener) {
        this.mListener = listener;
        executorService = Executors.newSingleThreadExecutor();
        mainHandler = new Handler(Looper.getMainLooper());
        onPreExecute();//开始
        Callable<String> downloadTask = new Callable<String>() {
            @Override
            public String call() throws Exception {
                //true 执行压缩成功，false 执行压缩失败
                return doInBackground(srcPath, destPath);
            }
        };
        Future<String> future = executorService.submit(downloadTask);
        new Thread(() -> {
            try {
                final String result = future.get(); // Get result ，doInBackground的返回值
                // Simulate onPostExecute
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        onPostExecute(result);
                    }
                });
            } catch (ExecutionException | InterruptedException e) {
                LogUtil.e("", "压缩异常：" + e.getMessage());
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * 开始：在主线程中执行，在任务开始前调用。
     */
    protected void onPreExecute() {
        if (mListener != null) {
            mListener.onStart();
        }
    }

    /**
     * 执行中：在后台线程中执行，用于执行耗时操作。
     *
     * @param paths paths[0]是srcPath, paths[1]是destPath
     */
    protected String doInBackground(String... paths) {
        //result:true压缩成功，false压缩失败
        boolean result = VideoController.getInstance().convertVideo(paths[0], paths[1], mQuality, new VideoController.CompressProgressListener() {
            @Override
            public void onProgress(float percent) {
                publishProgress(percent);
            }
        });
        return String.valueOf(result);
    }


    /**
     * 执行进度： 在主线程中执行，用于更新进度信息。
     *
     * @param progress
     */
    protected void onProgressUpdate(float progress) {
        // Code to update UI with progress information
        if (mListener != null) {
            mListener.onProgress(progress);
        }
    }

    /**
     * 执行进度:方法用于发布进度信息，并在主线程中调用 onProgressUpdate 方法来更新UI
     *
     * @param progress
     */
    protected void publishProgress(float progress) {
        // Update UI with progress
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                onProgressUpdate(progress);
            }
        });
    }

    /**
     * 完成:在主线程中执行，在任务完成后调用。
     * result：true：压缩成功，false压缩失败，是 downloadTask 的 call()的返回值，便于处理结果
     */
    protected void onPostExecute(String result) {
        // Code to execute after the background task has finished
        if (mListener != null) {
            if ("true".equals(result)) {
                mListener.onSuccess();
            } else {
                mListener.onFail();
            }
        }
    }

    /**
     * 在Activity的onDestroy中调用关闭加载
     */
    public void closeExecutor() {
        if (!executorService.isShutdown()) {
            executorService.shutdown();
        }
    }

    public interface CompressListener {
        void onStart();

        void onSuccess();

        void onFail();

        void onProgress(float percent);
    }
}
